package com.alex.seo.dao.group;

import java.util.List;
import java.util.Set;

import javax.persistence.MappedSuperclass;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;

import org.hibernate.Session;

import com.alex.seo.dao.AbstractHibernateDaoImpl;
import com.alex.seo.domain.group.SiteGroup;
import com.alex.seo.domain.group.SiteGroupItem;
import com.alex.seo.domain.site.Site;

@MappedSuperclass
@NamedQueries(value = {
		@NamedQuery(query = "select s.id from SiteGroupItem i inner join i.site s inner join i.siteGroup g where g.id=:id", name = "getSitesIdsOfGroupById"),
		@NamedQuery(query = "select s.id from SiteGroupItem i inner join i.site s inner join i.siteGroup g where g.name=:name", name = "getSitesIdsOfGroupByName"),
		@NamedQuery(query = "select s from SiteGroupItem i inner join i.site s inner join i.siteGroup g where g.id in :groupIds", name = "getSitesOfGroupsByIds"),
		@NamedQuery(query = "select g from SiteGroup g where g.name=:name", name = "getGroupByName") })
public class SiteGroupHibernateDao extends AbstractHibernateDaoImpl<SiteGroup, Integer> implements SiteGroupDao {

	@Override
	public void addSitesToGroup(List<Site> sites, SiteGroup siteGroup) {
		Session session = sessionFactory.getCurrentSession();
		for (Site site : sites) {
			session.persist(new SiteGroupItem(site, siteGroup));
		}
	}

	@Override
	public void addSiteToGroup(Site site, SiteGroup siteGroup) {
		sessionFactory.getCurrentSession().persist(new SiteGroupItem(site, siteGroup));
	}

	@Override
	@SuppressWarnings("unchecked")
	public List<Integer> getSiteIdsOfGroup(int groupId) {
		return sessionFactory.getCurrentSession()
				.getNamedQuery("getSitesIdsOfGroupById")
				.setParameter("id", groupId)
				.list();
	}

	@Override
	@SuppressWarnings("unchecked")
	public List<Integer> getSitesIdsOfGroup(String groupName) {
		return sessionFactory.getCurrentSession()
				.getNamedQuery("getSitesIdsOfGroupByName")
				.setParameter("name", groupName)
				.list();
	}
	
	@Override
	@SuppressWarnings("unchecked")
	public List<Site> getSitesOfGroups(Set<Integer> siteGroupIds) {
		return sessionFactory.getCurrentSession()
				.getNamedQuery("getSitesOfGroupsByIds")
				.setParameterList("groupIds", siteGroupIds)
				.list();
	}

	@Override
	public SiteGroup getByName(String groupName) {
		return (SiteGroup) sessionFactory.getCurrentSession()
				.getNamedQuery("getGroupByName")
				.setParameter("name", groupName)
				.uniqueResult();
	}
}
